const { execSync } = require('child_process');
const { RushConfiguration } = require('@microsoft/rush-lib');
const fs = require('fs');
const rushConfig = RushConfiguration.loadFromDefaultLocation();
const projects = rushConfig.projects
const neepPublish = projects.filter(project => project.shouldPublish);
const configString = process.argv[2]; // 获取命令行第二个参数
if(!configString) return
const configArray = configString.split('-')
const environment = configArray[0]


const packagesToBuild = configArray.slice(2);
console.log(packagesToBuild);
function installBasePackages() {
  // execSync('npm install pnpm', { cwd: process.cwd(), stdio: 'inherit' });
  execSync('pnpm install', { cwd: process.cwd(), stdio: 'inherit' });
}
function installCommonPackages() {
  const commonPackageNames = ['@siluzan/components']
  const commonPackages = projects.filter((project) => {
    return commonPackageNames.includes(project.packageName)
  })
}
function publishPackage(project) {
  execSync('pnpm publish', { cwd: project.projectFolder, stdio: 'inherit' });
}

function publishPackages() {
  neepPublish.forEach(publishPackage);
}
function getPackageName(file) {
  const packageName = file.split('/')[1];
  return packageName;
}
function getChangedFiles() {
  const output = execSync('git diff --name-only HEAD^ HEAD', { encoding: 'utf-8' });
  return output.split('\n');
}
// function hasPackageChanges(packageName) {
//   const changedFiles = getChangedFiles();
//   return changedFiles.some(file => file.startsWith('apps/' + getPackageName(packageName)));
// }
function buildChangePackages() {
  packagesToBuild.forEach(package => {
    execSync(`turbo run build --scope ${package}`, { stdio: 'inherit' });
  });
}
function copyDistFile(project) {
  const distPath = `${project.projectFolder}/dist`;
  const targetPath = `./${project.packageName}`;
  if (fs.existsSync(targetPath)) {
    fs.rmSync(targetPath, { recursive: true });
  }
  if (!fs.existsSync(targetPath)) {
    fs.mkdirSync(targetPath, { recursive: true });
  }
  console.log('copy', distPath, targetPath)
  execSync(`cp -r ${distPath} ${targetPath}`, { stdio: 'inherit' });
}
function buildChangePackages() {
  const buildpackages = projects.filter(project => {
    return packagesToBuild.includes(getPackageName(project.packageName));
  })

  const buildCommand = buildpackages.reduce((a, b) => {
    const filter = b ? ` --filter=${b.packageName} ` : ''
    return a + filter
  }, `pnpm turbo run build-${environment}`)
  console.log(buildCommand);
  execSync(buildCommand, { stdio: 'inherit' });
  // 打包测试
  // 复制dist文件到跟目录下
  buildpackages.forEach(copyDistFile);
}

installBasePackages()
installCommonPackages()
buildChangePackages()
// publishPackages()
